package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ChatClient extends Thread {
    private static int clientsNumber;
    private static int n = 3234;
    private final String m = "/snd 0";

    public static synchronized int getClientsNumber() {
        return clientsNumber;
    }

    public void run() {
        clientsNumber++;
        try(final Socket socket = new Socket("localhost", 7777)) {

            new Thread() {
                private DataInputStream dis = new DataInputStream(socket.getInputStream());
                private String lastMessage;
                @Override public void run() {
                    while(true) {
                        try {
                            lastMessage = dis.readUTF();
                        } catch (IOException e) {break;}
                    }
                }
            }.start();

            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            n++;
//            dos.writeUTF("/reg " + n + " " + n);
            dos.writeUTF("/log " + n + " " + n);

            while(true) {
                dos.writeUTF(m);
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {}
        clientsNumber--;
    }
}